using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

public partial class PlayerShootingSystem : SystemBase
{

    public Action<object,EventArgs> OnShoot;
    protected override void OnCreate()
    {
        RequireForUpdate<Player>();
    }
    
    protected override void OnUpdate()
    {
        if (Input.GetKey(KeyCode.T))
        {
            Entity playerEntity = SystemAPI.GetSingletonEntity<Player>();
            EntityManager.SetComponentEnabled<Stunned>(playerEntity,true);
        }
        
        if (Input.GetKey(KeyCode.Y))
        {
            Entity playerEntity = SystemAPI.GetSingletonEntity<Player>();
            EntityManager.SetComponentEnabled<Stunned>(playerEntity,false);
        }
        
        if (!Input.GetKeyDown(KeyCode.Space))
        {
            return;
        }

        SpawnCubesConfig config = SystemAPI.GetSingleton<SpawnCubesConfig>();
        EntityCommandBuffer entityCommandBuffer = new EntityCommandBuffer(WorldUpdateAllocator);

        foreach (var (localTransform,entity) in SystemAPI.Query<RefRO<LocalTransform>>().WithAll<Player>().WithDisabled<Stunned>().WithEntityAccess())
        {
            Entity spawnedEntity = entityCommandBuffer.Instantiate(config.CubePrefabEntity);
            entityCommandBuffer.SetComponent(spawnedEntity,new LocalTransform
            {
                Position =  localTransform.ValueRO.Position,
                Rotation = quaternion.identity,
                Scale = 1
            });

            // OnShoot?.Invoke(entity, EventArgs.Empty);
            
            PlayerShootingManager.Instance.PlayerShoot(localTransform.ValueRO.Position);
        }
        
        entityCommandBuffer.Playback(EntityManager);
    }
}
